package com.epfly.promo.activity.impl.discount;

import com.epfly.iface.promo.activity.enums.DiscountTypeEnum;
import com.epfly.promo.activity.dao.ActivityFoodMapper;
import com.epfly.promo.activity.entity.ActivityEntity;
import com.epfly.promo.activity.entity.ActivityRuleEntity;
import com.epfly.promo.activity.feign.DataRestaurantFeignService;
import com.epfly.promo.activity.impl.discount.content.FoodRebate;
import com.google.common.collect.Sets;
import com.ifood.model.goods.param.response.food.FoodInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 6.菜品折扣
 * {@link DiscountTypeEnum#FOOD_REBATE}
 */
@Service
public class FoodRebateDiscountFunction extends AbstractDiscountFunction {

    @Resource
    private DataRestaurantFeignService dataRestaurantFeignService;

    @Resource
    private ActivityFoodMapper activityFoodMapper;

    @Override
    public BigDecimal doApply(ActivityWrapper activityWrapper, ActivityRuleEntity ruleEntity) {
        // 优惠总金额
        BigDecimal totalRebate = BigDecimal.ZERO;
        ActivityEntity activityEntity = activityWrapper.getActivityEntity();

        // 查出所有可享受折扣的菜品ID列表
        List<String> foodIdList = activityFoodMapper.findByActivityIdAndFoodIdList(activityEntity.getId(), activityWrapper.getFoodIdList());
        if (CollectionUtils.isNotEmpty(foodIdList)) { // 可享受折扣的菜品集合不为空
            // 查出菜品信息
            List<FoodInfo> foodList = dataRestaurantFeignService.findFoodByFoodIdList(Sets.newHashSet(foodIdList));

            FoodRebate foodRebate = gson.fromJson(ruleEntity.getRuleContent(), FoodRebate.class);

            for (FoodInfo foodInfo : foodList) {
                BigDecimal rebatedPrice = foodInfo.getVipPrice().multiply(foodRebate.getFixedDiscountPercent()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (foodInfo.getVipPrice().compareTo(rebatedPrice) > 0) { // 市价高于折扣价
                     totalRebate = totalRebate.add(foodInfo.getVipPrice().subtract(rebatedPrice));
                }
            }
        }

        return totalRebate;
    }

    @Override
    public Byte getDiscountType() {
        return DiscountTypeEnum.FOOD_REBATE.getKey();
    }
}
